﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MyLocalChurch.Business;
using MyLocalChurch.Constants;
using MyLocalChurch.Models;
using MyLocalChurch.Models.Enumerations;
using MyLocalChurch.Models.KidsChurch;
using MyLocalChurch.Resources;
using RKConsulting.Web.Helpers;

namespace MyLocalChurch.KidsChurch
{
    public partial class CheckIn : System.Web.UI.Page
    {
        private readonly MyContext _context = MyContextSingleton.Instance;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (Page.IsPostBack)
                return;

            lblMessage.Text = Request.QueryString[QueryParameters.Message] ?? string.Empty;

            InitializeChurchServices();
            InitializeKid();
        }

        protected void InitializeChurchServices()
        {
            var churchServices = _context.ChurchServices.ToList();

            ddlChurchServices.DataSource = churchServices;
            ddlChurchServices.DataTextField = "StartTime";
            ddlChurchServices.DataValueField = "Id";
            ddlChurchServices.DataBind();

            var churchServiceId = QueryHelper.GetNullableIntQueryParam(QueryParameters.ChurchServiceId);
            if (!churchServiceId.HasValue)
                return;

            ddlChurchServices.SelectedValue = churchServiceId.Value.ToString();
        }

        protected void InitializeKid()
        {
            var kidId = QueryHelper.GetNullableIntQueryParam(QueryParameters.KidId);
            if (!kidId.HasValue)
                return;

            var kid = KidManager.GetKid(_context, kidId.Value);
            if (kid == null)
                return;

            var barcode = BarcodeManager.GetValidBarcode(kid.Barcodes);
            if (barcode == null)
                return;

            txtBarcode.Text = barcode.Code;
            ShowKidInformation(kid);
        }

        protected void btnRefresh_Click(object sender, EventArgs e)
        {
            var kid = KidManager.GetKid(_context, txtBarcode.Text);
            ShowKidInformation(kid);
        }

        protected void txtBarcode_TextChanged(object sender, EventArgs e)
        {
            var kid = KidManager.GetKid(_context, txtBarcode.Text);
            ShowKidInformation(kid);
        }

        protected void ShowKidInformation(Kid kid)
        {
            if (kid == null)
            {
                updatePanel.Visible = false;
                panelControls.Visible = false;
                return;
            }

            lblFirstName.Text = kid.FirstName ?? string.Empty;
            lblMiddleName.Text = kid.MiddleName ?? string.Empty;
            lblLastName.Text = kid.LastName ?? string.Empty;
            lblNickName.Text = kid.NickName ?? string.Empty;
            lblGender.Text = ((Gender)kid.Gender).ToString();
            lblBirthDate.Text = kid.BirthDate.ToString("d");
            lblKidCategory.Text = KidManager.GetKidCategory(kid).ToString();
            txtAllergies.Text = kid.Allergies;
            txtAdditionalInformation.Text = kid.AdditionalInformation;

            if (kid.Photo != null)
            {
                Session[ImageHandler.SessionName] = kid.Photo.ImageData;
                var imageHandlerUrl = ConfigurationManager.AppSettings[AppSettingKeys.ImageHandlerUrl];
                ImagePreview.ImageUrl = imageHandlerUrl;
            }

            updatePanel.Visible = true;
            panelControls.Visible = true;
        }

        protected void btnCheckIn_Click(object sender, EventArgs e)
        {
            var startTime = ddlChurchServices.SelectedItem.Text;
            var churchService = _context.ChurchServices.FirstOrDefault(cs => cs.StartTime == startTime);

            if (churchService == null)
                return;

            var kid = KidManager.GetKid(_context, txtBarcode.Text);
            if (kid == null)
                return;

            var checkIn = CheckInOutManager.GetCheckInForCheckOut(kid.CheckInOuts);
            if (checkIn == null)
            {
                checkIn = new CheckInOut
                    {
                        CheckInTimeStamp = DateTime.Now,
                        ChurchService = churchService,
                        Kid = kid
                    };

                kid.CheckInOuts.Add(checkIn);
                _context.CheckInOuts.Add(checkIn);
                _context.SaveChanges();

                var message = HttpUtility.UrlEncode(string.Format(MyResource.CheckInSuccessful, kid));
                Response.Redirect(string.Concat("CheckIn.aspx?",
                                                QueryParameters.ChurchServiceId, "=", churchService.Id,
                                                "&", QueryParameters.Message, "=", message)
                    );
            }
            else
            {
                lblMessage.Text = string.Format(ValidationMessages.CheckInNotCheckedOut,
                                                kid, checkIn.CheckInTimeStamp);
            }
        }
    }
}